<template>
  <div>
          <!-- 面包屑区域 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>商品管理</el-breadcrumb-item>
          <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片区域 -->
      <el-card>
          <!-- 头部按钮以及搜索区域 -->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-input v-model="queryInfo.query" @clear="getGoodsList()" placeholder="请输入内容" clearable>
                  <el-button slot="append" icon="el-icon-search" @click="searchGoodsInfo"></el-button>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="addGoodsDialog">添加商品</el-button>
            </el-col>
          </el-row>
          <!-- 表格区域 -->
          <el-table :data="goodsList" style="width: 100%" border stripe>
              <el-table-column type="index" label="#" ></el-table-column>
              <el-table-column  prop="goods_name" label="商品名称" ></el-table-column>
              <el-table-column  prop="goods_price" label="商品价格（元）"></el-table-column>
              <el-table-column  prop="goods_weight" label="商品重量"></el-table-column>
              <el-table-column  prop="add_time" label="创建时间">
                <template slot-scope="scope">{{scope.row.add_time | dataFormat }}</template>
              </el-table-column>
              <el-table-column label="操作" width="180px">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary"  icon="el-icon-edit" @click="editGoodsInfo(scope.row.goods_id)"></el-button>
                  <el-button  size="mini"  type="danger"  icon="el-icon-delete" @click="deleteGoodsInfo(scope.row.goods_id)"></el-button>
                </template>
              </el-table-column>
          </el-table>
          <!-- 分页功能 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
      </el-card>
      <!--        修改商品的对话框-->
        <el-dialog title="修改商品信息" :visible.sync="editDialogVisible" width="50%">
          <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="90px">
            <!--            Form 组件提供了表单验证的功能，只需要通过 rules 属性传入约定的验证规则，并将 Form-Item 的 prop 属性设置为需校验的字段名即可。-->
            <!--            由于这里的用户名，处于禁用状态，因此不需要验证规则，所以不加上prop-->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="editForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price" >
              <el-input v-model="editForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight" >
              <el-input v-model="editForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" >
              <el-input v-model="editForm.goods_number"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editDialog">确 定</el-button>
           </span>
        </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 存放商品列表查询数据
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      total: 0,
      // 存放商品列表
      goodsList: [],
      editForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0
      },
      editDialogVisible: false,
      // 控制修改对话框的表单的验证规则对象
      editFormRules: {
        goods_name: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getGoodsList()
  },
  methods: {
    // 获取商品所有列表数据
    async getGoodsList () {
      const { data: res } = await this.$http.get('goods', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        this.$message.error('获取数据失败')
      } else {
        this.total = res.data.total
        this.goodsList = res.data.goods
        console.log(this.goodsList)
      }
    },
    // 点击按钮，搜索商品数据
    searchGoodsInfo () {
      this.getGoodsList()
    },
    // 添加商品按钮
    addGoodsDialog () {
      this.$router.push('/goods/add')
    },
    // 编辑按钮
    async editGoodsInfo (rowId) {
      const { data: res } = await this.$http.get(`goods/${rowId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('查询信息失败')
      } else {
        // 查询信息成功
        this.editForm = res.data
        // console.log(this.editForm)
        this.editDialogVisible = true
      }
    },
    // 修改对话框，点击提交按钮
    editDialog () {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          // 发起修改信息的数据请求
          const { data: res } = await this.$http.put(`goods/${this.editForm.goods_id}`, {
            goods_name: this.editForm.goods_name,
            goods_price: this.editForm.goods_price,
            goods_number: this.editForm.goods_number,
            goods_weight: this.editForm.goods_weight,
            goods_cat: this.editForm.goods_cat
          })
          // console.log(res)
          if (res.meta.status !== 200) {
            return this.$message.error('修改信息失败')
          } else {
            // 成功修改之后，1.关闭对话框
            this.editDialogVisible = false
            // 重新刷新数据列表
            this.getGoodsList()
            // 提示修改成功
            this.$message.success('修改成功')
          }
        } else {
          return false
        }
      })
    },
    // 删除按钮
    async deleteGoodsInfo (rowId) {
      // $confirm也需要按需导入，同时返回的是一个promise
      const confirmResult = await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => {
        return error
      })
      // 如果用户确认删除，返回字符串为confirm。否则返回为cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      } else {
        const { data: res } = await this.$http.delete(`goods/${rowId}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        } else {
          this.$message.success('删除成功')
          this.getGoodsList()
        }
      }
    },
    // 分页
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    // 分页
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    }
  }
}
</script>
<style scoped>
.el-breadcrumb{
    margin-bottom: 15px
}
.el-card{
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.5) !important
}
.el-row{
    margin-bottom: 15px
}
</style>
